/**
 * Workflow
 */
var Workflow ={
	language: {
		
		languageName: "Workflow",
		
		smdUrl: '../../backend/php/WiringEditor.smd',

		IDFields: [
			{"type": "string", inputParams: {"name": "ID", readonly:"readonly", label: "ID", typeInvite: "Workflow ID" } },
		],
		
		instanceFields: [
			{"type": "string", inputParams: {"name": "instance", readonly:"readonly", label: "instance", typeInvite: "Workflow instance" } },
		],
		
		propertiesFields: [
			{"type": "string", inputParams: {"name": "name", label: "Title", typeInvite: "Enter a title" } },
			{"type": "text", inputParams: {"name": "description", label: "Description", cols: 30} }
		],
		taskPropertiesFields: [
			{"type": "text", inputParams: {"name": "signature", label: "service URI", rows:2, cols: 30, typeInvite: "Enter service URI" } }
		],
		
		modules: [
		   {
		      "name": "input",
		      "container": {
		        "xtype": "WireIt.WebUIInputContainer",
		   		"title": "input",
		   		"fields": [
		   			{"type": "myType", "inputParams": {"label": "Value", "name": "input", "wirable": false, "value": { "type":"string","inputParams":{"typeInvite": "input value"}} }}
		   		],
		   		"terminals": [
      			   {"name": "out", "direction": [0,1], "offsetPosition": {"left": 86, "bottom": -15}, "ddConfig": {
                      "type": "output",
					  "allowedTypes": ["input"]
                   }
                  }
      		   ]
		      }
		   },
			{
				  "name": "output",
				  "container": {
					 "xtype": "WireIt.WebUIOutputContainer",
					"title": "output",
					"fields": [ 
						{"type": "myType", "inputParams": {"label": "Value", "name": "input", "wirable": false, "value": { "type":"string","inputParams":{"typeInvite": "output value"}} }}
					],
				"terminals": [
					   {"name": "in", "direction": [0,-1], "offsetPosition": {"left": 82, "top": -15 }, "ddConfig": {
						  "type": "input",
						  "allowedTypes": ["output"]
					   },
					   "nMaxWires": 1
					  }
					]
				  }
			   },
			   {
				  "name": "Task",
				  "container": {"xtype": "Workflow.Container"}
			   },
			   {	"name": "Script",
				  "container": {"xtype": "WireIt.ScriptContainer"}
			   },
			   {	"name": "Python",
				  "container": {"xtype": "WireIt.PythonContainer"}
			   },
			   {
				  "name": "comment",
				  "container": {
					 "xtype": "WireIt.WebUIFormContainer",
					"title": "Comment",
					"fields": [
						{"type": "text", "inputParams": {"label": "", "name": "comment", "wirable": false }}
					 ]
				  },
				  "value": {
					 "input": {
						"type":"url","inputParams":{}
					 }
				  }
			   },	   		   
				],
		antiprism:[
			{
				"name":"unipoly",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/unipoly"}				
			},
			{
				"name":"off2pov",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off2pov"}				
			},
			{
				"name":"off2eig",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off2eig"}				
			},
			{
				"name":"off2m",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off2m"}				
			},
			{
				"name":"off2vrml",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off2vrml"}				
			},
			{
				"name":"crds2off",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/crds2off"}				
			},
			{
				"name":"m2off",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/m2off"}				
			},
//			{
//				"name":"canonical",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/canonical"}				
//			},
			{
				"name":"conv_hull",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/conv_hull"}				
			},
//			{
//				"name":"conway",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/conway"}				
//			},
//			{
//				"name":"geodesic",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/geodesic"}				
//			},
//			{
//				"name":"iso_delta",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/iso_delta"}				
//			},
//			{
//				"name":"jitterbug",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/jitterbug"}				
//			},
			{
				"name":"johnson",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/johnson"}				
			},
			{
				"name":"kcycle",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/kcycle"}				
			},
//			{
//				"name":"lat_grid",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/lat_grid"}				
//			},
			{
				"name":"minmax",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/minmax"}				
			},
			{
				"name":"n_icons",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/n_icons"}				
			},
			{
				"name":"off_align",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_align"}				
			},
			{
				"name":"off_color",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_color"}				
			},
			{
				"name":"off_color_alt",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_color_alt"}				
			},
//			{
//				"name":"off_query",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_query"}				
//			},
			{
				"name":"off_report",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_report"}				
			},
			{
				"name":"off_trans",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_trans"}				
			},
			{
				"name":"off_util",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/off_util"}				
			},
//			{
//				"name":"packer",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/packer"}				
//			},
			{
				"name":"pol_recip",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/pol_recip"}				
			},
//			{
//				"name":"poly_kscope",
//				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/poly_kscope"}				
//			},
			{
				"name":"poly_weave",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/poly_weave"}				
			},
			{
				"name":"repel",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/repel"}				
			},
			{
				"name":"sph_rings",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/sph_rings"}				
			},
			{
				"name":"sph_saff",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/sph_saff"}				
			},
			{
				"name":"string_art",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/string_art"}				
			},
			{
				"name":"untitle2d",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/unitile2d"}				
			},
			{
				"name":"zono",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/zono"}				
			}			
			],
		LP_Solvers:[
			{
				"name":"Generator2",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/Generator2"}				
			},
			{
				"name":"LinearModel2",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/LinearModel2"}				
			},
			{
				"name":"lp_solve",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/lp_solve"}				
			},
			{
				"name":"lp_solve_lp_only",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/lp_solve_lp_only"}				
			},
			{
				"name":"lp2mps",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/lp2mps"}				
			},
			{
				"name":"glpk",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/glpk"}				
			},
			{
				"name":"glpk_lp_only",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/glpk_lp_only"}				
			},
			{
				"name":"PostRedLp",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/PostRedLp"}				
			}
		],
		Neos:[			
			{
				"name":"Neos Client",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/NeosClient"}				
			},
			{
				"name":"Neos List",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/NeosList"}				
			},
			{
				"name":"SDP Neos Client",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/SDPNeosClient"}				
			},
			{
				"name":"LP AMPL Neos Client",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/LP-AMPL-NeosClient"}				
			},
			{
				"name":"AMPL Neos Client",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/AMPL-NeosClient"}				
			},
			{
				"name":"GAMS Neos Client",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru/taras/astafiev/antiprism/GAMS-NeosClient"}				
			}
			
			
		],
		Misc:[
			{
				"name":"echo",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru:7979/services/echo"}				
			},
			{
				"name":"povray",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru:7979/services/povray"}				
			},
			{
				"name":"fib",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru:7979/services/fib"}				
			},
			{
				"name":"maxima",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru:9999/maxima"}				
			},
			{
				"name":"cat",
				"container":{"xtype": "Workflow.Container","service":"http://dcs.isa.ru:9999/cat"}				
			}
		]
		
	},
	/**
    * @method init
    * @static
    */
   init: function() {
   	//this.editor = new Workflow.WiringEditor(this.language);

   }
   
};

Workflow.WiringEditor = function(options) {

   Workflow.WiringEditor.superclass.constructor.call(this, options);
};

YAHOO.lang.extend(Workflow.WiringEditor, WireIt.WebUIWiringEditor, {
   
});


Workflow.Container = function(options, layer) {

   Workflow.Container.superclass.constructor.call(this, options, layer);
   
   //this.buildTextArea(options.codeText);
   
   this.buildTextArea(options.URL || "");
   
   if (this.textarea){
          if (options.resourceJSON) { //already downloaded data from terminal
             this.resourceJSON = options.resourceJSON;  
			 this.drawTerminals();
			 this.checkResourceExists();
			 this.setName();
			 this.onCollapseButton();
			 
          } else {
			//this.createTerminals();
		  }
		  if (options.service) {
		  	this.buildTextArea(options.service);
			this.createTerminals();
			this.onCollapseButton();
		  }
		 
	}
	
	
   
   // Reposition the terminals when the container is being resized
   this.ddResize.eventResize.subscribe(function(e, args) {
      this.positionTerminals();
	  this.redrawAllWires();
		
      YAHOO.util.Dom.setStyle(this.textarea, "height", (args[0][1]-70)+"px");
	  
   }, this, true);
};

YAHOO.extend(Workflow.Container, WireIt.WebUIContainer, {
   
   /**
    * Create the textarea for the resource URI
    * @method buildTextArea
    * @Input {String} URL
    */
   
   buildTextArea: function(URL) {
	//alert("buildTextArea");
      this.textarea = WireIt.cn('textarea', null, {width: "90%", height: "70px", border: "0", padding: "5px"}, URL);
      this.setBody(this.textarea);

      YAHOO.util.Event.addListener(this.textarea, 'change', this.createTerminals, this, true);
	  
	 var kl = new YAHOO.util.KeyListener(this.textarea,{keys:[13]},function(){
			this.textarea.setValue(this.textarea.value.replace(new RegExp("[\\n]*","g"),''));
			simulateEvent('blur',this.textarea);
		}.bind(this),'keyup');
      kl.enable();
   },
   
   render: function(){
   	Workflow.Container.superclass.render.call(this);
		//this.onCollapseButton();
   },
   
   /**
    * Create (and re-create) the terminals
    * @method createTerminals
    */
createTerminals: function() {
	this.removeAllTerminals();
	this.ddHandle.appendChild(this.loadingFlag);

		new Ajax.Request (location.href+"wf/proxy?url="+encodeURIComponent(this.textarea.value), {
		method:'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport){
			if(transport.responseText){
				
				var json = YAHOO.lang.JSON.parse(transport.responseText);
				this.resourceJSON = json;
				this.setName();
				this.drawTerminals();
				this.onResourceOK();
				this.ddHandle.removeChild(this.loadingFlag);
				this.initState();		
			}
			else{
				
				 //resource does not exist
				
				this.onResourceError();
				this.ddHandle.removeChild(this.loadingFlag);				
				
			}	
			
		}.bind(this),
			
		onFailure: function(transport){
			
			this.onResourceError();
			this.ddHandle.removeChild(this.loadingFlag);
						
			var response = transport.responseText || "no response text";
			  if (transport.status==404) {
			   alert("404 error\nUrl "+url);
			   //this.editor.log("404 error\nUrl "+url);

			   } else if (transport.status==400) {
				   alert("mistake in url "+url+"\n"+response);
				   //this.editor.log("mistake in url "+url+"\n"+response);
			   } else {
				   //alert('Create terminals: Could not load data from url '+transport.status +"\n"+transport.statusText);
				   //this.editor.log('Create terminals: Could not load data from url '+transport.status +"\n"+transport.statusText);
				    }
				}.bind(this)
		
		});

},

   /**
    * Draw the terminals
    * @method drawTerminals
    * Igor Lazarev
    */

drawTerminals: function() {
	
	var json = this.resourceJSON;
	
	//alert("length = " + json.inputs.length);
	//alert("Inputs: " + JSON.stringify(json.inputs));
	
	this.nInputs = 0;
	this.nOutputs = 0;
				
	// create input terminals
		
	for (var i in json.inputs){
		//alert("type: "+json.inputs[i].type);
		
		var color = "rgb(173, 216, 230)";
		var bordercolor ="#0000ff";
		var termType = json.inputs[i].type;
		
		if (termType=="string"){
			color = "rgb(239,224,95)";
		}
		else if (termType=="file"){
			color = "rgb(227,117,80)";
		}
		else if (termType=="boolean"){
			color = "rgb(107,95,59)";
		}
		else if (termType=="number"){
			color = "rgb(31,172,225)";
		}
		else if (termType=="integer"){
			color = "rgb(201,205,204)";
		}
		
		var term = this.addTerminal({xtype: "WireIt.util.WebUITerminalInput", "name": i + ':' + json.inputs[i].type, wireConfig:{"color":color, "bordercolor":bordercolor}});
		this.nInputs++;
	}
	
	for (var i in json.outputs){
		
		var color = "rgb(173, 216, 230)";
		var bordercolor ="#0000ff";
		var termType = json.outputs[i].type;
		
		if (termType=="string"){
			color = "rgb(239,224,95)";
		}
		else if (termType=="file"){
			color = "rgb(227,117,80)";
		}
		else if (termType=="boolean"){
			color = "rgb(107,95,59)";
		}
		else if (termType=="number"){
			color = "rgb(31,172,225)";
		}
		else if (termType=="integer"){
			color = "rgb(201,205,204)";
		}
		
		var term = this.addTerminal({xtype: "WireIt.util.WebUITerminalOutput", "name": i + ':' + json.outputs[i].type, wireConfig:{"color":color, "bordercolor":bordercolor} });
		this.nOutputs++;
	}
				
	if (this.terminals.length > 0) {
		this.positionTerminals();
	}	

	// Declare the new terminals to the drag'n drop handler (so the wires are moved around with the container)
	this.dd.setTerminals(this.terminals);
		
},

setName: function (){
	this.ddHandle.removeChild(this.title);
	this.title = WireIt.cn('span', null, null, this.resourceJSON.name);
	this.ddHandle.appendChild(this.title);
	this.title == "Task";
},

checkResourceExists: function() {
	new Ajax.Request (location.href+"wf/proxy?url="+encodeURIComponent(this.textarea.value), {
		method:'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport){
			if(transport.responseText){ //resource exists
				this.onResourceOK();
			}
			else{
				this.onResourceError();
			}
		}.bind(this),
			
		onFailure: function(transport){ //resource does not exist

			this.onResourceError();
						
			var response = transport.responseText || "no response text";
			  
			  if (transport.status==404) {
			   alert("404 error\nUrl "+url);
			   //this.editor.log("404 error\nUrl "+url);

			   } else if (transport.status==400) {
				   alert("mistake in url "+url+"\n"+response);
				   //this.editor.log("mistake in url "+url+"\n"+response);
			   } else {
				   //alert('checkResourceExists: Could not load data from url '+transport.status +"\n"+transport.statusText); //a bug on fuji
				   if(typeof(this.editor)!="undefined"){
					this.editor.log('checkResourceExists: Could not load data from url '+transport.status +"\n"+transport.statusText); 
					}
				}
				}.bind(this)
		});
},
   
   /**
    * Reposition the terminals
    * @method positionTerminals
    */
   positionTerminals: function() {

      var width = WireIt.getIntStyle(this.el, "width");
      //input intervals	  
	  if (this.nInputs > 0) {
		  var inputsInterval = Math.floor(width/(this.nInputs+1));
		  for(var i = 1 ; i < (this.terminals.length-this.nOutputs+1) ; i++) {
			 var term = this.terminals[i-1];
			 WireIt.sn(term.el, null, {position: "absolute", top: "-15px", left: (inputsInterval*(i)-15)+"px"});
		  }
	  }

	//output intervals
		  if (this.nOutputs > 0) {
		  var outputsInterval = Math.floor (width/(this.nOutputs+1));
			if (this.nInputs == 0){
					for(var i = 1 ; i < (this.nOutputs+1) ; i++) {
					var term = this.terminals[i-1];
					WireIt.sn(term.el, null, {position: "absolute", bottom: "-15px", left: (outputsInterval*(i)-15)+"px"});
			  } 
			}
			else {
				for(var i = 1 ; i < (this.nOutputs+1) ; i++) {
					var term = this.terminals[this.nInputs + i-1];
					WireIt.sn(term.el, null, {position: "absolute", bottom: "-15px", left: (outputsInterval*(i)-15)+"px"})
			  } 
			} 
		} 

    },
	
	onAddWire: function(event, args){
		Workflow.Container.superclass.onAddWire.call(this,event, args);
		this.initState();
	},
	
	onRemoveWire: function(event, args){
		Workflow.Container.superclass.onRemoveWire.call(this,event, args);
		this.initState();
	},
   
   /**
    * Extend the getConfig to add the "URL" property
    * @method getConfig
    */
   getConfig: function() {
      var obj = Workflow.Container.superclass.getConfig.call(this);
      obj.URL = this.textarea.value;
	  obj.resourceJSON = this.resourceJSON;
	  obj.type = "Task";
	  obj.name = this.resourceJSON.name;
	  
	  return obj;
   },
   
   onResourceError: function(){
	
		this.ddHandle.style.backgroundColor = "#CD0000";
		this.bodyEl.style.border ="2px solid #CD0000";
		this.state = "MISSING";
   },
   
   onResourceOK: function(){
	
		this.ddHandle.style.backgroundColor = "#3366CC";
		this.bodyEl.style.border ="2px solid #3366CC"
		this.state = "READY";
   },
   
   initState: function(){
 	//alert("initState");
   
   if(this.resourceJSON||this.service){
			//alert("this.resourceJSON: " + JSON.stringify(this.resourceJSON));
			var inputs = this.resourceJSON.inputs;
					
									
			for (name in inputs){
				if((inputs[name].optional==false)||(!inputs[name].optional)){
					 var term = this.getTerminal(name+":"+inputs[name].type);
					 if(term){
						//YAHOO.util.Dom.removeClass(term.el, "WireIt-Terminal-required");
						 
						requiredMark = WireIt.cn('div', {className: "WireIt-RequiredMark"} );
				 		if (term.el.hasChildNodes()){
							term.el.childNodes[0].remove();
						}
						
						this.setReady();
						
						if(term.wires.length<1){

							term.el.appendChild(requiredMark);
							this.setUnready();					
						}
						

					 }
				}
				if (inputs[name].description){
					var term = this.getTerminal(name+":"+inputs[name].type);
					if (term) {
						descriptionTooltip = new YAHOO.widget.Tooltip("descriptionTooltip", {
							effect: {
								effect: YAHOO.widget.ContainerEffect.FADE,
								duration: 0.30
							},
							context: term.el,
							text: name + ":" + inputs[name].type + " - " + inputs[name].description,
							showDelay: 500
						});
					} 
				}
				
				
				var outputs = this.resourceJSON.outputs;
				for (name in outputs) {
					if (outputs[name].description){
					var term = this.getTerminal(name+":"+outputs[name].type);
					if (term) {
						descriptionTooltip = new YAHOO.widget.Tooltip("descriptionTooltip", {
							effect: {
								effect: YAHOO.widget.ContainerEffect.FADE,
								duration: 0.30
							},
							context: term.el,
							text: name + ":" + outputs[name].type + " - " + outputs[name].description,
							showDelay: 500
						});
					} 
				}
				}			

			}
			
									
		}
	
   },
   
   initType: function() {
   	//a stub
   }
  
});
